package com.jetinno.jetinnosystem;

import android.annotation.TargetApi;
import android.app.Application;
import android.os.Build;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by zhangyuncai on 2023/3/28.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    //TAG
    public static final String TAG = "CrashHandler";
    //CrashHandler实例
    private static CrashHandler mCrashHandler;
    //程序的App对象
    public Application mApplication;
    //生命周期监听
    MyActivityLifecycleCallbacks mMyActivityLifecycleCallbacks = new MyActivityLifecycleCallbacks();

    /**
     * 私有构造函数
     */
    private CrashHandler() {

    }

    /**
     * 获取CrashHandler实例 ,单例模式
     *
     * @return
     * @since V1.0
     */
    public static CrashHandler getInstance() {
        if (mCrashHandler == null)
            mCrashHandler = new CrashHandler();
        return mCrashHandler;
    }

    public void init(Application application) {
        initCrashHandler(application);
    }

    /**
     * 初始化
     *
     * @since V1.0
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void initCrashHandler(Application application) {
        mApplication = application;
        mApplication.registerActivityLifecycleCallbacks(mMyActivityLifecycleCallbacks);
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);

    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            String crashInfo = getCrashInfo(ex);
            DogLog.logOperation(mApplication, crashInfo);
            //给Toast留出时间
            Thread.sleep(2800);
        } catch (InterruptedException e) {
            Log.e(TAG, "uncaughtException() InterruptedException:" + e);
        }

        mMyActivityLifecycleCallbacks.removeAllActivities();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
        System.gc();
    }


    /**
     * 得到程序崩溃的详细信息
     */
    public String getCrashInfo(Throwable ex) {
        Writer result = new StringWriter();
        PrintWriter printWriter = new PrintWriter(result);
        ex.setStackTrace(ex.getStackTrace());
        ex.printStackTrace(printWriter);
        printWriter.close();
        return result.toString();
    }
}
